<template>
  <div class="page">
    <van-search
      v-model="keyword"
      show-action
      placeholder="请输入搜索关键词"
      @cancel="$router.back()"
    />
    <div class="list">
      <FancySection 
        v-show="!keyword"
        :list="displayRecommendList"
        @click="jumpDetail"
      />

      <FancySection 
        v-show="!keyword"
        title="历史搜索"
        closeable
        v-model:list="historyList"
      />
      <van-cell-group>
        <van-cell
          v-for="item in displayCinemas"
          :key="item.cinemaId"
          :title="item.name"
          :value="item.districtName"
          :label="item.address"
          @click="jumpDetailByCinema(item)"
        />
      </van-cell-group>
      <div class="empty" v-if="keyword && displayCinemas.length === 0">
        <van-empty description="暂无数据" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import FancySection,{ type FancySectionItem} from '@/components/fancy-section/index.vue'
import { ref, computed,watchEffect,watch } from 'vue'
import store2 from 'store2'
import { useCinemaStore } from '@/stores/cinema'
import { getCinemaListRecommend } from '@/api/modules/cinema'
import { type Cinema } from '@/api/interface'

const cinemaStore = useCinemaStore()
const recommendList = ref<Cinema.Item[]>([])
const historyList = ref<FancySectionItem[]>(
  store2.session.get('cinemas-history-list') || []
)

//监听历史搜索数据的变化，写入本地存储
watch(historyList,(newValue)=>{  
  store2.session.set('cinemas-history-list',newValue)
})

const keyword = ref('')
const displayCinemas = computed(() => {
    if(!keyword.value){
        return []
    }

  return cinemaStore.items.filter((item) => item.name.includes(keyword.value))
})

const displayRecommendList = computed(() => {
  return recommendList.value.map((item) => ({
    id: item.cinemaId,
    text: item.name
  }))
  .splice(0,5)
})

watchEffect(() => {
    cinemaStore.getItems({cityId: 440300, ticketFlag: 0})
    getCinemaListRecommend({ cityId: 440300 }).then(result => {
      recommendList.value = result.cinemas
    })
})

function jumpDetail(data: FancySectionItem) {
  historyList.value.unshift(data)
  historyList.value = historyList.value.splice(0, 2)
}
//搜索列表
function jumpDetailByCinema(data:Cinema.Item){
  console.log('搜索列表点击',data);
  //将当前数据持久化本地存储一份
  historyList.value.unshift({id:data.cinemaId, text:data.name})
  historyList.value = historyList.value.splice(0,2)
}
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.list {
  flex: 1;
  overflow-y: auto;
}
</style>


